import styles from "./personal.module.scss";
import Icon from "@/components/icon";
import Header from "@/shared/header";
import Back from "@/shared/back";
import React, { memo, useRef, useState } from "react";
import {
  getUserProfile,
  updateUserPhoto,
  updateUserProfile,
} from "@/store/actions/profile";
import { useDispatch, useSelector } from "react-redux";
import { useInitialState } from "@/utils/use-initial-state";
import { DatePicker, Dialog, Popup, Toast } from "antd-mobile";
import { logout } from "@/store/actions/login";
import { useHistory } from "react-router-dom";
import EditInput from "./component/EditInput";
import dayjs from "dayjs";
import EditList from "./component/EditList";
const index = memo(() => {
  let dispatch = useDispatch();
  let history = useHistory();
  // 获取用户信息
  const { userProfile } = useInitialState(getUserProfile, "profile");
  const { photo, name, intro, gender, birthday } = userProfile;
  const [inputVisible, setInputVisible] = useState(false);
  // 控制生日选择器显示与隐藏的状态
  const [showBirthday, setShowBirthday] = useState(false);
  const fileRef = useRef<HTMLInputElement>(null); // 用于上传文件的引用
  // 修改昵称或者简介状态
  type InputPopup = {
    type: "" | "name" | "intro";
    value: string;
    visible: boolean;
  };

  // 修改头像或者性别状态
  type ListPopup = {
    type: "" | "photo" | "gender";
    visible: boolean;
  };
  // 控制输入弹框显示与隐藏的状态
  const [inputPopup, setInputPopup] = useState<InputPopup>({
    type: "",
    value: "",
    visible: false,
  });
  // 控制列表弹框显示与隐藏的状态
  const [listPopup, setListPopup] = useState<ListPopup>({
    type: "",
    visible: false,
  });

  // 关闭输入弹框
  const onInputHide = () => {
    setInputPopup({
      type: "",
      value: "",
      visible: false,
    });
  };
  // 显示昵称弹框
  const onInputShow = () => {
    setInputPopup({
      type: "name",
      value: name,
      visible: true,
    });
  };
  // 显示简介弹框
  const onIntroShow = () => {
    setInputPopup({
      type: "intro",
      value: intro,
      visible: true,
    });
  };
  // 显示性别弹框
  const onGenderShow = () => {
    setListPopup({
      type: "gender",
      visible: true,
    });
  };

  // 显示头像弹框
  const onPhotoShow = () => {
    setListPopup({
      type: "photo",
      visible: true,
    });
  };

  // 隐藏性别弹框
  const onGenderHide = () => {
    setListPopup({
      type: "",
      visible: false,
    });
  };

  // 显示生日选择器
  const onShowBirthday = () => {
    setShowBirthday(true);
  };

  // 隐藏生日选择器
  const onHideBirthday = () => {
    setShowBirthday(false);
  };

  // 更新用户信息（昵称、简介、性别、头像、生日）
  const onUpdateProfile = async (
    type: "name" | "intro" | "gender" | "photo" | "birthday",
    value: string
  ) => {
    if (type === "photo") {
      fileRef.current?.click();
    } else {
      await dispatch(updateUserProfile({ [type]: value }) as any);
      Toast.show({
        content: "更新成功",
        duration: 1000,
      });
    }
    // 关闭弹框
    onInputHide();
    onGenderHide();
  };

  // 更新生日
  const onUpdateBirthday = (value: Date) => {
    const birthday = dayjs(value).format("YYYY-MM-DD");
    onUpdateProfile("birthday", birthday);
    onHideBirthday();
  };

  // 更改头像
  const onChangePhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const photoData = new FormData();

    photoData.append("photo", file);

    await dispatch(updateUserPhoto(photoData) as any);
    onGenderHide();
  };
  // 退出登录相关逻辑
  const onLogout = () => {
    const handler = Dialog.show({
      title: "温馨提示",
      content: "亲，你确定退出吗？",
      actions: [
        [
          {
            key: "cancel",
            text: "取消",
            onClick: () => {
              handler.close();
            },
          },
          {
            key: "confirm",
            text: "退出",
            style: {
              color: "var(--adm-color-weak)",
            },
            onClick() {
              dispatch(logout() as any);
              handler.close();
              localStorage.removeItem("HomeListItem");
              history.replace("/login");
            },
          },
        ],
      ],
    });
  };
  return (
    <div className={styles.page}>
      <Header title="个人信息" left={<Back />} />
      <ul className={styles.options}>
        <li onClick={onPhotoShow}>
          <span>头像</span>
          <div className={styles.value}>
            <div className={styles.avatar}>
              <img src={photo} alt="avatar" />
            </div>
            <Icon type="iconbtn_right" className={styles.icon} />
          </div>
        </li>
        <li>
          <span>昵称</span>
          <div className={styles.value} onClick={onInputShow}>
            <span>{name ? name : "默认昵称"}</span>
            <Icon type="iconbtn_right" className={styles.icon} />
          </div>
        </li>
        <li>
          <span>简介</span>
          <div className={styles.value} onClick={onIntroShow}>
            <span>{intro ? intro : "默认简介"}</span>
            <Icon type="iconbtn_right" className={styles.icon} />
          </div>
        </li>
      </ul>
      <ul className={styles.options}>
        <li onClick={onGenderShow}>
          <span>性别</span>
          <div className={styles.value}>
            <span>{gender ? "女" : "男"}</span>
            <Icon type="iconbtn_right" className={styles.icon} />
          </div>
        </li>
        <li onClick={onShowBirthday}>
          <span>生日</span>
          <div className={styles.value}>
            <span>{birthday}</span>
            <Icon type="iconbtn_right" className={styles.icon} />
          </div>
        </li>
      </ul>
      <DatePicker
        visible={showBirthday}
        onCancel={onHideBirthday}
        onConfirm={onUpdateBirthday}
        value={new Date(birthday)}
        title="选择年月日"
        min={new Date(1900, 0, 1, 0, 0, 0)}
        max={new Date()}
      />
      <button className={styles.logout} onClick={onLogout}>
        退出登录
      </button>

      <Popup
        position="right"
        bodyStyle={{ width: "100vw" }}
        visible={inputPopup.visible}
        // 表示在关闭弹出层时，销毁组件内容
        destroyOnClose
      >
        <EditInput
          type={inputPopup.type}
          value={inputPopup.value}
          onClose={onInputHide}
          onUpdateProfile={onUpdateProfile}
          key={inputPopup.type}
        />
      </Popup>
      <Popup visible={listPopup.visible} onMaskClick={onGenderHide}>
        <EditList
          type={listPopup.type}
          onUpdateProfile={onUpdateProfile}
          onClose={onGenderHide}
        />
      </Popup>
      <div className="wrapper">
        <input type="file" hidden ref={fileRef} onChange={onChangePhoto} />
      </div>
    </div>
  );
});

export default index;
